﻿using PSI.Helper;
using PSI.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;

namespace PSI.Services {
    public class FIdService : PSIBaseService {
        /// <summary>
        /// 插入最近访问的功能编号
        /// </summary>
        /// <param name="fid">功能编号</param>
        public void InsertRecentFId(string fid) {
            var user = UserService.GetLoginUser();

            var sql = @"insert into psi_recent_fid (user_id, fid, dt) 
                        values(@userId, @fid, @dt)";
            var p = CreateDbParameters();
            p.AddWithValue("userId", user.Id);
            p.AddWithValue("fid", fid);
            p.AddWithValue("dt", DateTime.Now);

            Execute(sql, p);
        }

        /// <summary>
        /// 返回当前用户使用最多的十个功能
        /// </summary>
        /// <returns></returns>
        public List<FId> GetRecentFid() {
            var result = new List<FId>();

            var user = UserService.GetLoginUser();

            var sql = @"
                    select f.id, f.name
                    from (select top 10 fid as fid, count(fid) as c
                    from psi_recent_fid
                    where user_id = @userId
                    group by fid
                    order by c desc ) v, psi_fid f
                    where v.fid = f.id
                    ";
            var p = CreateDbParameters();
            p.AddWithValue("userId", user.Id);
            Query(sql, p, reader => {
                result.Add(new FId {
                    Id = reader.GetString(0),
                    Name = reader.GetString(1)
                });
            });

            return result;
        }
    }
}